import 'dart:convert';

import 'package:dio/dio.dart';
import 'package:flutter_book/data/model/base_response_model.dart';

import 'api.dart';
import 'package:flutter_book/util/extensions/string_extensions.dart';

Future<T?> requestYckApi<T>(Uri uri,
    {var data, String requestMethod = METHOD_GET, CancelToken? token, BaseOptions? baseOptions}) async {
  BaseResponseModel responseModel;

  try {
    Map<String, dynamic> queryParameters = jsonDecode(data);
    responseModel = await _requestApi(uri.toString(), queryParameters, requestMethod, token);
  } catch (e) {
    responseModel = await _requestYckApi(uri, data, requestMethod, baseOptions, token);
  }

  if (responseModel.isSuccess) {
    return responseModel.data;
  } else {
    // "没有获取到了数据:${uri.path},$requestMethod".print;
    // "没有获取到了数据:${responseModel.message}".print;
    return null;
  }
}

//通用的请求api的方法，请在具体的子api中进行入参封装和结果处理 authType只在特定的接口中赋值
Future<BaseResponseModel> _requestApi(String path, Map<String, dynamic> queryParameters,
    [String requestMethod = METHOD_GET, CancelToken? token]) async {
  BaseResponseModel baseResponseModel = new BaseResponseModel();
  try {
    Response response;
    if (requestMethod == METHOD_GET) {
      setHeaders(getDioGetInstance());
      response = await getDioGetInstance().get(path, queryParameters: queryParameters, cancelToken: token);
    } else {
      setHeaders(getDioPostInstance());
      response = await getDioPostInstance().post(path, queryParameters: queryParameters, cancelToken: token);
    }
    baseResponseModel.data = response.data;
    baseResponseModel.isSuccess = true;
  } on DioError catch (e) {
    baseResponseModel.isSuccess = false;
    baseResponseModel.message = requestMethod + "," + e.message;
  } catch (e) {
    baseResponseModel.isSuccess = false;
    baseResponseModel.message = requestMethod + "," + "Unknown error";
  }
  return baseResponseModel;
}

//通用的请求api的方法，请在具体的子api中进行入参封装和结果处理 authType只在特定的接口中赋值
Future<BaseResponseModel> _requestYckApi(Uri uri,
    [var data, String requestMethod = METHOD_GET, BaseOptions? baseOptions, CancelToken? token]) async {
  BaseResponseModel baseResponseModel = new BaseResponseModel();
  try {
    Response response;
    if (requestMethod == METHOD_GET) {
      setHeaders(getDioGetInstance(), baseOptions);
      response = await getDioGetInstance().getUri(uri, cancelToken: token);
    } else {
      setHeaders(getDioPostInstance(), baseOptions);
      response = await getDioPostInstance().postUri(uri, data: data, cancelToken: token);
    }
    baseResponseModel.data = response.data;
    baseResponseModel.isSuccess = true;
  } on DioError catch (e) {
    baseResponseModel.isSuccess = false;
    baseResponseModel.message = requestMethod + "," + e.message;
  } catch (e) {
    baseResponseModel.isSuccess = false;
    baseResponseModel.message = requestMethod + "," + "Unknown error";
  }
  return baseResponseModel;
}
